package com.mbl.base.modular.mall.service.impl;

import com.mbl.base.modular.mall.constant.CouponConstant;
import com.mbl.base.modular.mall.entity.Coupon;
import com.mbl.base.modular.mall.entity.CouponUser;
import com.mbl.base.modular.mall.mapper.CouponMapper;
import com.mbl.base.modular.mall.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mbl.base.modular.mall.service.ICouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 优惠券信息及规则表 服务实现类
 * </p>
 *
 * @author lwj
 * @since 2020-03-22
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Autowired
    private ICouponUserService couponUserService;

    @Override
    public Coupon checkCoupon(Long userId, Long couponId, Long userCouponId, BigDecimal checkedGoodsPrice) {
        Coupon coupon = super.getById(couponId);
        if (coupon == null) {
            return null;
        }
        // 查询具体发放的优惠卷
        CouponUser couponUser = couponUserService.getById(userCouponId);
        if (couponUser == null) {
            couponUser = couponUserService.queryOne(userId, couponId);
        } else if (!couponId.equals(couponUser.getCouponId())) { // 优惠卷有效验证
            return null;
        }
        if (couponUser == null) {
            return null;
        }

        // 检查是否超期
        Integer timeType = coupon.getTimeType();
        Integer days = coupon.getDays();
        LocalDateTime now = LocalDateTime.now();
        if (timeType.equals(CouponConstant.TIME_TYPE_TIME)) {
            if (now.isBefore(coupon.getStartTime()) || now.isAfter(coupon.getEndTime())) {
                return null;
            }
        }
        else if(timeType.equals(CouponConstant.TIME_TYPE_DAYS)) {
            LocalDateTime expired = couponUser.getCreateTime().plusDays(days);
            if (now.isAfter(expired)) {
                return null;
            }
        }
        else {
            return null;
        }

        // 检测商品是否符合
        // TODO 目前仅支持全平台商品，所以不需要检测
        Integer goodType = coupon.getGoodsType();
        if (!goodType.equals(CouponConstant.GOODS_TYPE_ALL)) {
            return null;
        }

        // 检测订单状态
        Integer status = coupon.getStatus();
        if (!status.equals(CouponConstant.STATUS_NORMAL)) {
            return null;
        }
        // 检测是否满足最低消费
        if (checkedGoodsPrice.compareTo(coupon.getMin()) == -1) {
            return null;
        }

        return coupon;
    }
}
